﻿#region Imports

using System;
using N2;
using N2.Collections;
using N2.Edit;
using N2.Edit.Web;

#endregion

namespace AWS.N2CMS.Tags
{
    [ToolbarPlugin("TAGS", "tags", "Plugins/Tags/Manage.aspx?selected={selected}", ToolbarArea.Preview, Targets.Preview,
        "~/Content/Plugins/Tags/tag_green.png", 100,
        AuthorizedRoles = new[] {"Editors", "Administrators", "Admin"},
        ToolTip = "Manage and browse all tags",
        GlobalResourceClassName = "Toolbar")]
    public partial class Manage : EditPage
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            tagsDataSource.Query = Find.Items.Where.Type.Eq(typeof (Tag)).OrderBy.Name.Asc;
            tagsDataSource.Inserted += delegate { gvTags.DataBind(); };
            tagsDataSource.Updated += delegate { gvTags.DataBind(); };
            tagsDataSource.Deleted += delegate { gvTags.DataBind(); };
            tagsDataSource.Deleting += ItemDeleting;
        }

        protected void ItemDeleting(object sender, ItemListEventArgs e)
        {
            foreach (var item in e.Items)
            {
                N2.Context.Persister.Delete(item);
            }
        }

        protected void AddTag(object sender, EventArgs e)
        {
            var tagName = tbTagName.Text.Trim();

            if (string.IsNullOrEmpty(tagName)) return;

            var tags = Find.Items.Where.Type.Eq(typeof (Tag)).And.Name.Eq(tagName.ToLower()).Select<Tag>();

            if (tags.Count > 0) return;

            //the tag doesn't exist, do lets add it.
            var tag = N2.Context.Current.Definitions.CreateInstance<Tag>(null);
            tag.Name = tagName.ToLower();
            tag.Title = tagName;

            N2.Context.Persister.Save(tag);

            gvTags.DataBind();

            //var selectionUtility = new SelectionUtility(HttpContext.Current.Request, N2.Context.Current);

            //HttpContext.Current.Response.Redirect(
            //    Context.Current.EditManager.GetEditExistingItemUrl(selectionUtility.SelectedItem));
        }
    }
}